import React from 'react';
import {injectIntl} from './intl';
import PropTypes from 'prop-types';
import {Button, Form, Row, Col, Modal, Card, Spin, message, Table} from 'antd';
import routes from './routes';
import {FORM_OPTIONS, PAGE, TABLE} from '../constants';
import {uuid, conventEnumValueToString, exportDownload} from '../utils';
import {PERMISSION} from './constants';
import WrappedSelect from '../common/WrappedSelect';
import styles from './style.css';
import {validateAdd, generateRowSpanData} from './utils';
import Return from '../common/Return';
import ClaimSelectPanel from './ClaimSelectPanel';
import {exportUsedPartDestory} from './api';
import TextInput from 'Shared/components/TextInput';
import {currency} from '../Enum';
const FormItem = Form.Item;
const EMPTY_ARRAY = [];
export class Submit extends React.PureComponent {
    state = {
        loading: false,
        hasOperat: false,
        isValidate: false,
        showPanel: false,
        submitedComment: '',
    };

    componentDidMount() {
        this.props.init();
        this.ismounted = true;
    }

    componentWillUnmount() {
        this.ismounted = false;
        this.props.onUmount();
    }

    handleFilterChange = (value, name) => {
        if(!this.state.hasOperat)
            this.setState({
                hasOperat: true
            });
        this.props.onConditionsChange(name, value);
    };
    // eslint-disable-next-line react/sort-comp
    onChange = (value, name, e) => {
        const {applyid, id} = e.target.dataset;
        const data = {
            value,
            claimId: applyid,
            id
        };
        this.props.onConditionsChange(name, data);
    }
    showPanel = () => {
        this.setState({
            showPanel: !this.state.showPanel
        });
    };
    onClickExportBtn = () => {
        this.setState({loading: true});
        exportUsedPartDestory(this.props.id).then(res => {
            this.setState({loading: false});
            exportDownload(res.data);
        });
    }

    onSelectClaim = (data = EMPTY_ARRAY) => {
        this.props.onSelectClaim(data);
    };

    onClickSubmit = () => {
        const result = validateAdd(this.props.conditions, this.props.id);
        if(!this.props.conditions.submitedComment || !this.props.conditions.submitedComment.trim()) {
            this.setState({isValidate: true});
            return message.warn(this.props.intl.formatMessage({
                id: 'submit.submitedComment.validate',
                defaultMessage: '下发意见不能为空'
            }));
        }
        if(result) {
            this.setState({
                isValidate: true,
            });
            return message.warn(result);
        }
        this.setState({
            loading: true
        });
        this.props.onClickSubmit().then(success => {
            if(this.ismounted && !success)
                this.setState({
                    loading: false
                });
        });
    };
    render() {
        const operations = [];
        const {details = EMPTY_ARRAY} = this.props.conditions;
        const currentSelectRowKeys = details.map(item => item.claimId);
        const columns = [
            {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.claimCode',
                    defaultMessage: '索赔单号'
                }),
                dataIndex: 'claimCode',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.subDealerCode',
                    defaultMessage: '经销商编号'
                }),
                dataIndex: 'subDealerCode',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.subDealerName',
                    defaultMessage: '经销商名称'
                }),
                dataIndex: 'subDealerName',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text && record.rowSpan ? record.rowSpan : 0,
                    },
                })
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.usedPartBarCode',
                    defaultMessage: '旧件条码'
                }),
                dataIndex: 'usedPartBarCode',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.usedPartCode',
                    defaultMessage: '备件号'
                }),
                dataIndex: 'usedPartCode',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.usedPartName',
                    defaultMessage: '备件名称'
                }),
                dataIndex: 'usedPartName',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.quantity',
                    defaultMessage: '数量'
                }),
                dataIndex: 'quantity',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.unit',
                    defaultMessage: '单位'
                }),
                dataIndex: 'unit',
            }, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.remark',
                    defaultMessage: '备注'
                }),
                dataIndex: 'remark',
            }
        ];
        if(!this.props.isDealerUser)
            columns.splice(3, 0, {
                title: this.props.intl.formatMessage({
                    id: 'commonDetail.column.claimSignedRemark',
                    defaultMessage: '索赔标记备注'
                }),
                dataIndex: 'claimSignedRemark',
                render: (text, record) => ({
                    children: text,
                    props: {
                        rowSpan: text ? record.rowSpan : 0,
                    },
                })
            }); 
        return (
            <div className={styles.detail}>
                <Modal
                    title={this.props.intl.formatMessage({
                        id: 'add.claimModal.title',
                        defaultMessage: '维修索赔单查询'
                    })}
                    width="80%"
                    maskClosable={false}
                    footer={null}
                    wrapClassName={styles.dataSelectModal}
                    destroyOnClose={true}
                    visible={this.state.showPanel}
                    onCancel={this.showPanel}>
                    <ClaimSelectPanel
                        brandId={this.props.conditions.brandId}
                        dealerId={this.props.conditions.dealerId}
                        supplierId={this.props.conditions.supplierId}
                        currentSelectRowKeys={currentSelectRowKeys}
                        onSelect={this.props.onSelectClaim}
                        afterSubmit={this.showPanel} />
                </Modal>
                <Spin spinning={this.props.loading || this.state.loading}>
                    <Form className="form-standard">
                        <Card
                            className={styles.marginBottom}
                            title={this.props.intl.formatMessage({
                                id: 'add.card.title',
                                defaultMessage: '基本信息'
                            })}>
                            <Row>
                                <Col key="code" {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.code',
                                            defaultMessage: '编号'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.id ? this.props.conditions.code : this.props.intl.formatMessage({
                                            id: 'add.form.code.noData',
                                            defaultMessage: '<尚未生成>'
                                        })}</span>
                                    </FormItem>
                                </Col>
                                {this.props.brands.length > 1 ? <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'add.form.brandId',
                                            defaultMessage: '品牌'
                                        })}
                                        {...FORM_OPTIONS.item}
                                        validateStatus={this.state.isValidate && !this.props.conditions.brandId ? 'error' : null}
                                        required={!this.props.id}>
                                        {this.props.id ? <span className="value-font">{this.props.conditions.brandCode}</span>
                                            : <WrappedSelect
                                                name="brandId"
                                                value={this.props.conditions.brandId}
                                                options={this.props.brands}
                                                onChange={this.handleFilterChange} />}
                                    </FormItem>
                                </Col> : null}
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.dealerId ? 'error' : null}
                                        required={!this.props.id}
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.dealerId',
                                            defaultMessage: '总代'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.dealerCode}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        validateStatus={this.state.isValidate && !this.props.conditions.supplierId ? 'error' : null}
                                        required={!this.props.id}
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.supplierId',
                                            defaultMessage: '供应商'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.supplierCode}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem
                                        label={this.props.intl.formatMessage({
                                            id: 'queryPanel.form.currency',
                                            defaultMessage: '币种'
                                        })}
                                        {...FORM_OPTIONS.item}>
                                        <span className="value-font">{conventEnumValueToString(currency, this.props.conditions.currency)}</span>
                                    </FormItem>
                                </Col>
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'queryPanel.form.remark',
                                        defaultMessage: '备注'
                                    })}{...FORM_OPTIONS.item}>
                                        <span className="value-font">{this.props.conditions.remark}</span>
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                        <Card
                            title={this.props.intl.formatMessage({
                                id: 'add.details',
                                defaultMessage: '销毁单清单'
                            })}
                            extra={<div>
                                <Button onClick={this.onClickExportBtn} size="small">
                                    {this.props.intl.formatMessage({
                                        id: 'add.btn.export',
                                        defaultMessage: '导出'
                                    })}
                                </Button>
                            </div>}>
                            <Table
                                className="white-space-nowrap"
                                rowKey="id"
                                columns={columns}
                                pagination={false}
                                dataSource={details}
                                {...TABLE} />
                        </Card>
                    </Form>
                    <Form className="form-standard">
                        <Card
                            className={styles.marginBottom}
                            extra={operations}
                            title={this.props.intl.formatMessage({
                                id: 'submit.card.submitedComment',
                                defaultMessage: '下发意见'
                            })}>
                            <Row className="radio-group-validate">
                                <Col {...FORM_OPTIONS.col}>
                                    <FormItem label={this.props.intl.formatMessage({
                                        id: 'submit.form.submitedComment',
                                        defaultMessage: '下发意见'
                                    })} {...FORM_OPTIONS.item} required
                                    validateStatus={this.state.isValidate && !this.state.submitedComment ? 'error' : null}>
                                        <TextInput type="textarea" id="submitedComment" value={this.state.submitedComment} onBlur={this.handleFilterChange} />
                                    </FormItem>
                                </Col>
                            </Row>
                        </Card>
                    </Form>
                </Spin>
                <div className="page-toolbar">
                    <Return
                        disabled={this.state.loading}
                        showWarning={this.state.hasOperat}
                        onConfirm={this.props.onCancel} />
                </div>
                {this.props.submitable && (
                    <Card type="inner">
                        <Row>
                            <Col className="col-align-right">
                                <Button
                                    key="submit"
                                    loading={this.state.loading}
                                    onClick={this.onClickSubmit}
                                    type="primary">
                                    {this.props.intl.formatMessage({
                                        id: 'add.btn.submit',
                                        defaultMessage: '保存'
                                    })}
                                </Button>
                            </Col>
                        </Row>
                    </Card>
                )}
            </div>
        );
    }
}
Submit.propTypes = {
    brands: PropTypes.array.isRequired,
    conditions: PropTypes.object.isRequired,
    init: PropTypes.func.isRequired,
    loading: PropTypes.bool.isRequired,
    submitable: PropTypes.bool.isRequired,
    onCancel: PropTypes.func.isRequired,
    onClickSubmit: PropTypes.func.isRequired,
    onConditionsChange: PropTypes.func.isRequired,
    onDeleteAll: PropTypes.func.isRequired,
    onDeleteDetail: PropTypes.func.isRequired,
    onSelectClaim: PropTypes.func.isRequired,
    onUmount: PropTypes.func.isRequired,
    intl: PropTypes.object
};
import {connect} from 'react-redux';
import {
    saveSubmitCondition,
    clearData,
    tableSearch,
    onClickSubmit,
    getEditInitData,
    selectClaim,
    deleteAllDetail,
    deleteDetail,
} from './actions';
import {createSelector} from 'reselect';

const getSubmitData = createSelector(
    state => state.getIn(['page', 'appState', 'submitData']),
    data => {
        const conditions = data.toJS() || {};
        const {details = [], ...props} = conditions;
        const newDetails = generateRowSpanData(details, 'claimId', ['claimCode', 'claimSignedRemark', 'subDealerCode', 'subDealerName']);
        return {
            ...props,
            details: newDetails.map(item => ({
                id: item.id || uuid(),
                ...item,
            }))
        };
    }
);

const getBrands = createSelector(
    state => state.getIn(['page', 'domainData', 'brands', 'data']),
    brands => {
        const data = brands.toJS() || EMPTY_ARRAY;
        return data.map(item => ({
            value: item.id,
            text: item.name
        }));
    }
);

const getPermissions = createSelector(
    state => state.getIn(['page', 'domainData', 'permission', 'data']),
    (state, ownProps) => ownProps.id,
    state => state.getIn(['page', 'domainData', 'detail', 'data']),
    (permissions, id, detail) => {
        const {options = EMPTY_ARRAY} = detail.toJS();
        const data = permissions.toJS();
        const submitable = id ? data.includes(PERMISSION.update) && options.includes(PERMISSION.update)
            : data.includes(PERMISSION.add);
        return submitable;
    }
);
const mapStateToProps = (state, ownProps) => ({
    id: ownProps.id,
    submitable: getPermissions(state, ownProps),
    isDealerUser: state.getIn(['page', 'domainData', 'initData', 'isDealerUser']),
    loading: state.getIn(['page', 'domainData', 'detail', 'isFetching']),
    conditions: getSubmitData(state),
    brands: getBrands(state),
});

const mapDispatchToProps = (dispatch, ownProps) => ({
    init: () => dispatch(getEditInitData(ownProps.id)),
    onConditionsChange: (name, value) => dispatch(saveSubmitCondition(name, value)),
    onClickSubmit: () =>
        dispatch(onClickSubmit(ownProps.id, ownProps.isSubmit)).then(res => {
            if(res.ok) {
                dispatch(tableSearch({
                    pageIndex: PAGE.index
                }));
                ownProps.history.push(routes.query.url());
            }
            return res.ok;
        }),
    onCancel: () => {
        ownProps.history.push(routes.query.url());
    },
    onUmount: () => dispatch(clearData()),
    onSelectClaim: data => dispatch(selectClaim(data)),
    onDeleteAll: () => dispatch(deleteAllDetail()),
    onDeleteDetail: data => dispatch(deleteDetail(data)),
});


export default connect(
    mapStateToProps,
    mapDispatchToProps
)(injectIntl(Submit));
